"""应用配置模块

基于Pydantic Settings的配置管理
支持环境变量和.env文件配置
"""

import os
from typing import List, Optional
from pydantic_settings import BaseSettings
from dotenv import load_dotenv

# 确保在创建Settings实例前加载.env文件
env_file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), '.env')
load_dotenv(env_file_path)


class Settings(BaseSettings):
    """应用配置类
    
    使用Pydantic Settings进行配置管理
    支持从环境变量和.env文件读取配置
    """
    
    # 数据库配置
    db_host: str = "localhost"
    db_port: int = 3306
    db_name: str = "brain_wave_db"
    db_user: str = "root"
    db_password: str = ""
    
    # 数据库连接池配置
    db_max_connections: int = 20  # 最大连接数
    db_stale_timeout: int = 300   # 连接空闲超时时间(秒)
    db_timeout: int = 30          # 查询超时时间(秒)
    db_connect_timeout: int = 10  # 连接超时时间(秒)
    
    # 应用配置
    app_name: str = "DataBridge API"
    app_version: str = "1.0.0"
    app_host: str = "0.0.0.0"
    app_port: int = 8000
    debug: bool = True
    
    # API配置
    api_prefix: str = "/api/v1"
    
    # 安全配置
    secret_key: str = "your-secret-key-change-in-production"
    access_token_expire_minutes: int = 30
    algorithm: str = "HS256"
    
    # 日志配置
    log_level: str = "INFO"
    log_file: str = "logs/app.log"
    log_rotation: str = "1 day"
    log_retention: str = "30 days"
    
    # CORS配置
    allowed_origins: List[str] = ["http://localhost:3000", "http://127.0.0.1:3000"]
    allowed_methods: List[str] = ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
    allowed_headers: List[str] = ["*"]
    
    # HTTP客户端配置
    http_timeout: float = 10.0
    http_timeout_long: float = 30.0
    
    # 数据查询配置
    default_query_limit: int = 100
    max_query_limit: int = 1000
    
    # 数据库字段长度限制
    max_id_length: int = 50
    max_session_id_length: int = 100
    max_room_id_length: int = 36
    max_user_id_length: int = 50
    max_sleep_state_length: int = 20
    
    # 测试配置
    test_base_url: str = "http://localhost:8000"
    test_max_duration: float = 1.0
    test_max_retries: int = 3
    test_retry_delay: float = 0.1
    
    # 数据处理配置
    eeg_signal_max_amplitude: int = 50
    
    # 内存缓存配置
    memory_cache_ttl_seconds: int = 30
    memory_cache_cleanup_interval_seconds: int = 10
    
    class Config:
        env_file = ".env"
        env_file_encoding = "utf-8"
        case_sensitive = False
        extra = "ignore"  # 忽略额外的环境变量
    
    @property
    def database_url(self) -> str:
        """获取数据库连接URL"""
        return f"mysql://{self.db_user}:{self.db_password}@{self.db_host}:{self.db_port}/{self.db_name}"
    
    def ensure_log_directory(self):
        """确保日志目录存在"""
        log_dir = os.path.dirname(self.log_file)
        if log_dir and not os.path.exists(log_dir):
            os.makedirs(log_dir, exist_ok=True)


# 创建全局配置实例
settings = Settings()